# lama/lama_algorithm.py

import networkx as nx
from .community_utils import get_neighbors, compute_node_score, expand_community
from .optimization import update_z_and_U, objective_function, learn_delta_weights


def lama_community_detection(G, seed_node, max_iter=50, alpha=0.5, threshold=0.5):
    """
    使用 LAMA ://d:\WeChat Files\wxid_73sx4ec43h6922\FileStorage\File\2025-03\end\_internal\grakel\datasets\index.html#L1-L85)
    """
    # 初始化核心集 C、边界 N 和外壳 NN
    C = [seed_node]
    N = list(get_neighbors(G, seed_node))
    NN = []

    # 初始化节点归属值 z(u) ∈ [0,1]
    z = {node: 0.5 for node in G.nodes() if node != seed_node}
    z[seed_node] = 1.0  # 种子节点归属为1

    U = {node: 0.5 for node in G.nodes()}  # 统一从属关系
    delta_w = {'PPI': alpha, 'Expression': 1 - alpha}  # 每个网络的权重

    for _ in range(max_iter):
        # 扩展局部社区
        new_nodes = expand_community(C, N, G, z, threshold=threshold)

        # 更新 C, N, NN
        C.extend(new_nodes)
        N = list(set(N) - set(new_nodes))
        NN = list(set(nx.node_boundary(G, C)))  # 获取新的边界节点

        # 更新邻居节点的 z 值
        for node in N:
            z[node] = compute_node_score(G, node, C, z, delta_w)

        # 更新统一从属关系 U
        U = update_z_and_U(z, U, alpha)

        # 更新阈值或收敛条件
        if not new_nodes:
            break

    return C, z, U


if __name__ == "__main__":
    # 示例运行
    G = nx.readwrite.edgelist.read_weighted_edgelist("results/fused_network.txt", nodetype=int)
    seed_node = 813  # 示例种子节点
    community, _, _ = lama_community_detection(G, seed_node)
    print(f"检测到的社区包含 Entrez ID: {community}")
